Add, update, tweak documentation
[lhc/web/wiklou.git] / includes / ImagePage.php
1 <?php
2 /**
3 * Class for viewing MediaWiki file description pages
4 *
5 * @ingroup Media
6 */
7 class ImagePage extends Article {
8
9 /**
10 * @var File
11 */
12 private $displayImg;
13 /**
14 * @var FileRepo
15 */
16 private $repo;
17 private $fileLoaded;
18
19 var $mExtraDescription = false;
20
21 /**
22 * @param $title Title
23 * @return WikiFilePage
24 */
25 protected function newPage( Title $title ) {
26 // Overload mPage with a file-specific page
27 return new WikiFilePage( $title );
28 }
29
30 /**
31 * Constructor from a page id
32 * @param $id Int article ID to load
33 */
34 public static function newFromID( $id ) {
35 $t = Title::newFromID( $id );
36 # @todo FIXME: Doesn't inherit right
37 return $t == null ? null : new self( $t );
38 # return $t == null ? null : new static( $t ); // PHP 5.3
39 }
40
41 /**
42 * @param $file File:
43 * @return void
44 */
45 public function setFile( $file ) {
46 $this->mPage->setFile( $file );
47 $this->displayImg = $file;
48 $this->fileLoaded = true;
49 }
50
51 protected function loadFile() {
52 if ( $this->fileLoaded ) {
53 return true;
54 }
55 $this->fileLoaded = true;
56
57 $this->displayImg = $img = false;
58 wfRunHooks( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg ) );
59 if ( !$img ) { // not set by hook?
60 $img = wfFindFile( $this->getTitle() );
61 if ( !$img ) {
62 $img = wfLocalFile( $this->getTitle() );
63 }
64 }
65 $this->mPage->setFile( $img );
66 if ( !$this->displayImg ) { // not set by hook?
67 $this->displayImg = $img;
68 }
69 $this->repo = $img->getRepo();
70 }
71
72 /**
73 * Handler for action=render
74 * Include body text only; none of the image extras
75 */
76 public function render() {
77 global $wgOut;
78 $wgOut->setArticleBodyOnly( true );
79 parent::view();
80 }
81
82 public function view() {
83 global $wgOut, $wgShowEXIF, $wgRequest, $wgUser;
84
85 $diff = $wgRequest->getVal( 'diff' );
86 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
87
88 if ( $this->getTitle()->getNamespace() != NS_FILE || ( isset( $diff ) && $diffOnly ) ) {
89 return parent::view();
90 }
91
92 $this->loadFile();
93
94 if ( $this->getTitle()->getNamespace() == NS_FILE && $this->mPage->getFile()->getRedirected() ) {
95 if ( $this->getTitle()->getDBkey() == $this->mPage->getFile()->getName() || isset( $diff ) ) {
96 // mTitle is the same as the redirect target so ask Article
97 // to perform the redirect for us.
98 $wgRequest->setVal( 'diffonly', 'true' );
99 return parent::view();
100 } else {
101 // mTitle is not the same as the redirect target so it is
102 // probably the redirect page itself. Fake the redirect symbol
103 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
104 $wgOut->addHTML( $this->viewRedirect( Title::makeTitle( NS_FILE, $this->mPage->getFile()->getName() ),
105 /* $appendSubtitle */ true, /* $forceKnown */ true ) );
106 $this->mPage->viewUpdates();
107 return;
108 }
109 }
110
111 $this->showRedirectedFromHeader();
112
113 if ( $wgShowEXIF && $this->displayImg->exists() ) {
114 // @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
115 $formattedMetadata = $this->displayImg->formatMetadata();
116 $showmeta = $formattedMetadata !== false;
117 } else {
118 $showmeta = false;
119 }
120
121 if ( !$diff && $this->displayImg->exists() ) {
122 $wgOut->addHTML( $this->showTOC( $showmeta ) );
123 }
124
125 if ( !$diff ) {
126 $this->openShowImage();
127 }
128
129 # No need to display noarticletext, we use our own message, output in openShowImage()
130 if ( $this->mPage->getID() ) {
131 # NS_FILE is in the user language, but this section (the actual wikitext)
132 # should be in page content language
133 $pageLang = $this->getTitle()->getPageLanguage();
134 $wgOut->addHTML( Xml::openElement( 'div', array( 'id' => 'mw-imagepage-content',
135 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
136 'class' => 'mw-content-'.$pageLang->getDir() ) ) );
137 parent::view();
138 $wgOut->addHTML( Xml::closeElement( 'div' ) );
139 } else {
140 # Just need to set the right headers
141 $wgOut->setArticleFlag( true );
142 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
143 $this->mPage->viewUpdates();
144 }
145
146 # Show shared description, if needed
147 if ( $this->mExtraDescription ) {
148 $fol = wfMessage( 'shareddescriptionfollows' );
149 if ( !$fol->isDisabled() ) {
150 $wgOut->addWikiText( $fol->plain() );
151 }
152 $wgOut->addHTML( '<div id="shared-image-desc">' . $this->mExtraDescription . "</div>\n" );
153 }
154
155 $this->closeShowImage();
156 $this->imageHistory();
157 // TODO: Cleanup the following
158
159 $wgOut->addHTML( Xml::element( 'h2',
160 array( 'id' => 'filelinks' ),
161 wfMsg( 'imagelinks' ) ) . "\n" );
162 $this->imageDupes();
163 # @todo FIXME: For some freaky reason, we can't redirect to foreign images.
164 # Yet we return metadata about the target. Definitely an issue in the FileRepo
165 $this->imageLinks();
166
167 # Allow extensions to add something after the image links
168 $html = '';
169 wfRunHooks( 'ImagePageAfterImageLinks', array( $this, &$html ) );
170 if ( $html ) {
171 $wgOut->addHTML( $html );
172 }
173
174 if ( $showmeta ) {
175 $wgOut->addHTML( Xml::element( 'h2', array( 'id' => 'metadata' ), wfMsg( 'metadata' ) ) . "\n" );
176 $wgOut->addWikiText( $this->makeMetadataTable( $formattedMetadata ) );
177 $wgOut->addModules( array( 'mediawiki.action.view.metadata' ) );
178 }
179
180 // Add remote Filepage.css
181 if( !$this->repo->isLocal() ) {
182 $css = $this->repo->getDescriptionStylesheetUrl();
183 if ( $css ) {
184 $wgOut->addStyle( $css );
185 }
186 }
187 // always show the local local Filepage.css, bug 29277
188 $wgOut->addModuleStyles( 'filepage' );
189 }
190
191 public function getDisplayedFile() {
192 $this->loadFile();
193 return $this->displayImg;
194 }
195
196 /**
197 * Create the TOC
198 *
199 * @param $metadata Boolean: whether or not to show the metadata link
200 * @return String
201 */
202 protected function showTOC( $metadata ) {
203 $r = array(
204 '<li><a href="#file">' . wfMsgHtml( 'file-anchor-link' ) . '</a></li>',
205 '<li><a href="#filehistory">' . wfMsgHtml( 'filehist' ) . '</a></li>',
206 '<li><a href="#filelinks">' . wfMsgHtml( 'imagelinks' ) . '</a></li>',
207 );
208 if ( $metadata ) {
209 $r[] = '<li><a href="#metadata">' . wfMsgHtml( 'metadata' ) . '</a></li>';
210 }
211
212 wfRunHooks( 'ImagePageShowTOC', array( $this, &$r ) );
213
214 return '<ul id="filetoc">' . implode( "\n", $r ) . '</ul>';
215 }
216
217 /**
218 * Make a table with metadata to be shown in the output page.
219 *
220 * @todo FIXME: Bad interface, see note on MediaHandler::formatMetadata().
221 *
222 * @param $metadata Array: the array containing the EXIF data
223 * @return String The metadata table. This is treated as Wikitext (!)
224 */
225 protected function makeMetadataTable( $metadata ) {
226 $r = "<div class=\"mw-imagepage-section-metadata\">";
227 $r .= wfMsgNoTrans( 'metadata-help' );
228 $r .= "<table id=\"mw_metadata\" class=\"mw_metadata\">\n";
229 foreach ( $metadata as $type => $stuff ) {
230 foreach ( $stuff as $v ) {
231 # @todo FIXME: Why is this using escapeId for a class?!
232 $class = Sanitizer::escapeId( $v['id'] );
233 if ( $type == 'collapsed' ) {
234 $class .= ' collapsable';
235 }
236 $r .= "<tr class=\"$class\">\n";
237 $r .= "<th>{$v['name']}</th>\n";
238 $r .= "<td>{$v['value']}</td>\n</tr>";
239 }
240 }
241 $r .= "</table>\n</div>\n";
242 return $r;
243 }
244
245 /**
246 * Overloading Article's getContent method.
247 *
248 * Omit noarticletext if sharedupload; text will be fetched from the
249 * shared upload server if possible.
250 */
251 public function getContent() {
252 $this->loadFile();
253 if ( $this->mPage->getFile() && !$this->mPage->getFile()->isLocal() && 0 == $this->getID() ) {
254 return '';
255 }
256 return parent::getContent();
257 }
258
259 protected function openShowImage() {
260 global $wgOut, $wgUser, $wgImageLimits, $wgRequest,
261 $wgLang, $wgEnableUploads;
262
263 $this->loadFile();
264
265 $sizeSel = intval( $wgUser->getOption( 'imagesize' ) );
266 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
267 $sizeSel = User::getDefaultOption( 'imagesize' );
268
269 // The user offset might still be incorrect, specially if
270 // $wgImageLimits got changed (see bug #8858).
271 if ( !isset( $wgImageLimits[$sizeSel] ) ) {
272 // Default to the first offset in $wgImageLimits
273 $sizeSel = 0;
274 }
275 }
276 $max = $wgImageLimits[$sizeSel];
277 $maxWidth = $max[0];
278 $maxHeight = $max[1];
279 $dirmark = $wgLang->getDirMark();
280
281 if ( $this->displayImg->exists() ) {
282 # image
283 $page = $wgRequest->getIntOrNull( 'page' );
284 if ( is_null( $page ) ) {
285 $params = array();
286 $page = 1;
287 } else {
288 $params = array( 'page' => $page );
289 }
290 $width_orig = $this->displayImg->getWidth( $page );
291 $width = $width_orig;
292 $height_orig = $this->displayImg->getHeight( $page );
293 $height = $height_orig;
294
295 $longDesc = wfMsg( 'parentheses', $this->displayImg->getLongDesc() );
296
297 wfRunHooks( 'ImageOpenShowImageInlineBefore', array( &$this, &$wgOut ) );
298
299 if ( $this->displayImg->allowInlineDisplay() ) {
300 # image
301
302 # "Download high res version" link below the image
303 # $msgsize = wfMsgHtml( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime );
304 # We'll show a thumbnail of this image
305 if ( $width > $maxWidth || $height > $maxHeight ) {
306 # Calculate the thumbnail size.
307 # First case, the limiting factor is the width, not the height.
308 if ( $width / $height >= $maxWidth / $maxHeight ) {
309 $height = round( $height * $maxWidth / $width );
310 $width = $maxWidth;
311 # Note that $height <= $maxHeight now.
312 } else {
313 $newwidth = floor( $width * $maxHeight / $height );
314 $height = round( $height * $newwidth / $width );
315 $width = $newwidth;
316 # Note that $height <= $maxHeight now, but might not be identical
317 # because of rounding.
318 }
319 $msgbig = wfMsgHtml( 'show-big-image' );
320 $otherSizes = array();
321 foreach ( $wgImageLimits as $size ) {
322 if ( $size[0] < $width_orig && $size[1] < $height_orig &&
323 $size[0] != $width && $size[1] != $height ) {
324 $otherSizes[] = $this->makeSizeLink( $params, $size[0], $size[1] );
325 }
326 }
327 $msgsmall = wfMessage( 'show-big-image-preview' )->
328 rawParams( $this->makeSizeLink( $params, $width, $height ) )->
329 parse() . ' ' .
330 Html::rawElement( 'span', array( 'class' => 'mw-filepage-other-resolutions' ),
331 wfMessage( 'show-big-image-other' )->
332 rawParams( $wgLang->pipeList( $otherSizes ), count( $otherSizes ) )->parse()
333 );
334 } else {
335 # Image is small enough to show full size on image page
336 $msgsmall = wfMessage( 'file-nohires' )->parse();
337 }
338
339 $params['width'] = $width;
340 $params['height'] = $height;
341 $thumbnail = $this->displayImg->transform( $params );
342
343 $showLink = true;
344 $anchorclose = Html::rawElement( 'div', array( 'class' => 'mw-filepage-resolutioninfo' ), $msgsmall );
345
346 $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
347 if ( $isMulti ) {
348 $wgOut->addHTML( '<table class="multipageimage"><tr><td>' );
349 }
350
351 if ( $thumbnail ) {
352 $options = array(
353 'alt' => $this->displayImg->getTitle()->getPrefixedText(),
354 'file-link' => true,
355 );
356 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
357 $thumbnail->toHtml( $options ) .
358 $anchorclose . "</div>\n" );
359 }
360
361 if ( $isMulti ) {
362 $count = $this->displayImg->pageCount();
363
364 if ( $page > 1 ) {
365 $label = $wgOut->parse( wfMsg( 'imgmultipageprev' ), false );
366 $link = Linker::link(
367 $this->getTitle(),
368 $label,
369 array(),
370 array( 'page' => $page - 1 ),
371 array( 'known', 'noclasses' )
372 );
373 $thumb1 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
374 array( 'page' => $page - 1 ) );
375 } else {
376 $thumb1 = '';
377 }
378
379 if ( $page < $count ) {
380 $label = wfMsg( 'imgmultipagenext' );
381 $link = Linker::link(
382 $this->getTitle(),
383 $label,
384 array(),
385 array( 'page' => $page + 1 ),
386 array( 'known', 'noclasses' )
387 );
388 $thumb2 = Linker::makeThumbLinkObj( $this->getTitle(), $this->displayImg, $link, $label, 'none',
389 array( 'page' => $page + 1 ) );
390 } else {
391 $thumb2 = '';
392 }
393
394 global $wgScript;
395
396 $formParams = array(
397 'name' => 'pageselector',
398 'action' => $wgScript,
399 'onchange' => 'document.pageselector.submit();',
400 );
401
402 for ( $i = 1; $i <= $count; $i++ ) {
403 $options[] = Xml::option( $wgLang->formatNum( $i ), $i, $i == $page );
404 }
405 $select = Xml::tags( 'select',
406 array( 'id' => 'pageselector', 'name' => 'page' ),
407 implode( "\n", $options ) );
408
409 $wgOut->addHTML(
410 '</td><td><div class="multipageimagenavbox">' .
411 Xml::openElement( 'form', $formParams ) .
412 Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) .
413 wfMsgExt( 'imgmultigoto', array( 'parseinline', 'replaceafter' ), $select ) .
414 Xml::submitButton( wfMsg( 'imgmultigo' ) ) .
415 Xml::closeElement( 'form' ) .
416 "<hr />$thumb1\n$thumb2<br clear=\"all\" /></div></td></tr></table>"
417 );
418 }
419 } else {
420 # if direct link is allowed but it's not a renderable image, show an icon.
421 if ( $this->displayImg->isSafeFile() ) {
422 $icon = $this->displayImg->iconThumb();
423
424 $wgOut->addHTML( '<div class="fullImageLink" id="file">' .
425 $icon->toHtml( array( 'file-link' => true ) ) .
426 "</div>\n" );
427 }
428
429 $showLink = true;
430 }
431
432 if ( $showLink ) {
433 $filename = wfEscapeWikiText( $this->displayImg->getName() );
434 $linktext = $filename;
435 if ( isset( $msgbig ) ) {
436 $linktext = wfEscapeWikiText( $msgbig );
437 }
438 $medialink = "[[Media:$filename|$linktext]]";
439
440 if ( !$this->displayImg->isSafeFile() ) {
441 $warning = wfMsgNoTrans( 'mediawarning' );
442 $wgOut->addWikiText( <<<EOT
443 <div class="fullMedia"><span class="dangerousLink">{$medialink}</span>$dirmark <span class="fileInfo">$longDesc</span></div>
444 <div class="mediaWarning">$warning</div>
445 EOT
446 );
447 } else {
448 $wgOut->addWikiText( <<<EOT
449 <div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">$longDesc</span>
450 </div>
451 EOT
452 );
453 }
454 }
455
456 if ( !$this->displayImg->isLocal() ) {
457 $this->printSharedImageText();
458 }
459 } else {
460 # Image does not exist
461 if ( $wgEnableUploads && $wgUser->isAllowed( 'upload' ) ) {
462 // Only show an upload link if the user can upload
463 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
464 $nofile = array(
465 'filepage-nofile-link',
466 $uploadTitle->getFullURL( array( 'wpDestFile' => $this->mPage->getFile()->getName() ) )
467 );
468 } else {
469 $nofile = 'filepage-nofile';
470 }
471 // Note, if there is an image description page, but
472 // no image, then this setRobotPolicy is overriden
473 // by Article::View().
474 $wgOut->setRobotPolicy( 'noindex,nofollow' );
475 $wgOut->wrapWikiMsg( "<div id='mw-imagepage-nofile' class='plainlinks'>\n$1\n</div>", $nofile );
476 if ( !$this->getID() ) {
477 // If there is no image, no shared image, and no description page,
478 // output a 404, to be consistent with articles.
479 $wgRequest->response()->header( 'HTTP/1.1 404 Not Found' );
480 }
481 }
482 $wgOut->setFileVersion( $this->displayImg );
483 }
484
485 /**
486 * Creates an thumbnail of specified size and returns an HTML link to it
487 * @param array $params Scaler parameters
488 * @param int $width
489 * @param int $height
490 */
491 private function makeSizeLink( $params, $width, $height ) {
492 $params['width'] = $width;
493 $params['height'] = $height;
494 $thumbnail = $this->displayImg->transform( $params );
495 if ( $thumbnail && !$thumbnail->isError() ) {
496 return Html::rawElement( 'a', array(
497 'href' => $thumbnail->getUrl(),
498 'class' => 'mw-thumbnail-link'
499 ), wfMessage( 'show-big-image-size' )->numParams(
500 $thumbnail->getWidth(), $thumbnail->getHeight()
501 )->parse() );
502 } else {
503 return '';
504 }
505 }
506
507 /**
508 * Show a notice that the file is from a shared repository
509 */
510 protected function printSharedImageText() {
511 global $wgOut;
512
513 $this->loadFile();
514
515 $descUrl = $this->mPage->getFile()->getDescriptionUrl();
516 $descText = $this->mPage->getFile()->getDescriptionText();
517
518 /* Add canonical to head if there is no local page for this shared file */
519 if( $descUrl && $this->mPage->getID() == 0 ) {
520 $wgOut->addLink( array( 'rel' => 'canonical', 'href' => $descUrl ) );
521 }
522
523 $wrap = "<div class=\"sharedUploadNotice\">\n$1\n</div>\n";
524 $repo = $this->mPage->getFile()->getRepo()->getDisplayName();
525
526 if ( $descUrl && $descText && wfMsgNoTrans( 'sharedupload-desc-here' ) !== '-' ) {
527 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-here', $repo, $descUrl ) );
528 } elseif ( $descUrl && wfMsgNoTrans( 'sharedupload-desc-there' ) !== '-' ) {
529 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload-desc-there', $repo, $descUrl ) );
530 } else {
531 $wgOut->wrapWikiMsg( $wrap, array( 'sharedupload', $repo ), ''/*BACKCOMPAT*/ );
532 }
533
534 if ( $descText ) {
535 $this->mExtraDescription = $descText;
536 }
537 }
538
539 public function getUploadUrl() {
540 $this->loadFile();
541 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
542 return $uploadTitle->getFullURL( array(
543 'wpDestFile' => $this->mPage->getFile()->getName(),
544 'wpForReUpload' => 1
545 ) );
546 }
547
548 /**
549 * Print out the various links at the bottom of the image page, e.g. reupload,
550 * external editing (and instructions link) etc.
551 */
552 protected function uploadLinksBox() {
553 global $wgUser, $wgOut, $wgEnableUploads, $wgUseExternalEditor;
554
555 if ( !$wgEnableUploads ) {
556 return;
557 }
558
559 $this->loadFile();
560 if ( !$this->mPage->getFile()->isLocal() ) {
561 return;
562 }
563
564 $wgOut->addHTML( "<br /><ul>\n" );
565
566 # "Upload a new version of this file" link
567 if ( UploadBase::userCanReUpload( $wgUser, $this->mPage->getFile()->name ) ) {
568 $ulink = Linker::makeExternalLink( $this->getUploadUrl(), wfMsg( 'uploadnewversion-linktext' ) );
569 $wgOut->addHTML( "<li id=\"mw-imagepage-reupload-link\"><div class=\"plainlinks\">{$ulink}</div></li>\n" );
570 }
571
572 # External editing link
573 if ( $wgUseExternalEditor ) {
574 $elink = Linker::link(
575 $this->getTitle(),
576 wfMsgHtml( 'edit-externally' ),
577 array(),
578 array(
579 'action' => 'edit',
580 'externaledit' => 'true',
581 'mode' => 'file'
582 ),
583 array( 'known', 'noclasses' )
584 );
585 $wgOut->addHTML(
586 '<li id="mw-imagepage-edit-external">' . $elink . ' <small>' .
587 wfMsgExt( 'edit-externally-help', array( 'parseinline' ) ) .
588 "</small></li>\n"
589 );
590 }
591
592 $wgOut->addHTML( "</ul>\n" );
593 }
594
595 protected function closeShowImage() { } # For overloading
596
597 /**
598 * If the page we've just displayed is in the "Image" namespace,
599 * we follow it with an upload history of the image and its usage.
600 */
601 protected function imageHistory() {
602 global $wgOut;
603
604 $this->loadFile();
605 $pager = new ImageHistoryPseudoPager( $this );
606 $wgOut->addHTML( $pager->getBody() );
607 $wgOut->preventClickjacking( $pager->getPreventClickjacking() );
608
609 $this->mPage->getFile()->resetHistory(); // free db resources
610
611 # Exist check because we don't want to show this on pages where an image
612 # doesn't exist along with the noimage message, that would suck. -ævar
613 if ( $this->mPage->getFile()->exists() ) {
614 $this->uploadLinksBox();
615 }
616 }
617
618 protected function queryImageLinks( $target, $limit ) {
619 $dbr = wfGetDB( DB_SLAVE );
620
621 return $dbr->select(
622 array( 'imagelinks', 'page' ),
623 array( 'page_namespace', 'page_title', 'page_is_redirect', 'il_to' ),
624 array( 'il_to' => $target, 'il_from = page_id' ),
625 __METHOD__,
626 array( 'LIMIT' => $limit + 1, 'ORDER BY' => 'il_from', )
627 );
628 }
629
630 protected function imageLinks() {
631 global $wgOut, $wgLang;
632
633 $limit = 100;
634
635 $res = $this->queryImageLinks( $this->getTitle()->getDbKey(), $limit + 1);
636 $rows = array();
637 $redirects = array();
638 foreach ( $res as $row ) {
639 if ( $row->page_is_redirect ) {
640 $redirects[$row->page_title] = array();
641 }
642 $rows[] = $row;
643 }
644 $count = count( $rows );
645
646 $hasMore = $count > $limit;
647 if ( !$hasMore && count( $redirects ) ) {
648 $res = $this->queryImageLinks( array_keys( $redirects ),
649 $limit - count( $rows ) + 1 );
650 foreach ( $res as $row ) {
651 $redirects[$row->il_to][] = $row;
652 $count++;
653 }
654 $hasMore = ( $res->numRows() + count( $rows ) ) > $limit;
655 }
656
657 if ( $count == 0 ) {
658 $wgOut->wrapWikiMsg(
659 Html::rawElement( 'div',
660 array( 'id' => 'mw-imagepage-nolinkstoimage' ), "\n$1\n" ),
661 'nolinkstoimage'
662 );
663 return;
664 }
665
666 $wgOut->addHTML( "<div id='mw-imagepage-section-linkstoimage'>\n" );
667 if ( !$hasMore ) {
668 $wgOut->addWikiMsg( 'linkstoimage', $count );
669 } else {
670 // More links than the limit. Add a link to [[Special:Whatlinkshere]]
671 $wgOut->addWikiMsg( 'linkstoimage-more',
672 $wgLang->formatNum( $limit ),
673 $this->getTitle()->getPrefixedDBkey()
674 );
675 }
676
677 $wgOut->addHTML(
678 Html::openElement( 'ul',
679 array( 'class' => 'mw-imagepage-linkstoimage' ) ) . "\n"
680 );
681 $count = 0;
682
683 // Sort the list by namespace:title
684 usort( $rows, array( $this, 'compare' ) );
685
686 // Create links for every element
687 $currentCount = 0;
688 foreach( $rows as $element ) {
689 $currentCount++;
690 if ( $currentCount > $limit ) {
691 break;
692 }
693
694 $link = Linker::linkKnown( Title::makeTitle( $element->page_namespace, $element->page_title ) );
695 if ( !isset( $redirects[$element->page_title] ) ) {
696 $liContents = $link;
697 } else {
698 $ul = "<ul class='mw-imagepage-redirectstofile'>\n";
699 foreach ( $redirects[$element->page_title] as $row ) {
700 $currentCount++;
701 if ( $currentCount > $limit ) {
702 break;
703 }
704
705 $link2 = Linker::linkKnown( Title::makeTitle( $row->page_namespace, $row->page_title ) );
706 $ul .= Html::rawElement(
707 'li',
708 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
709 $link2
710 ) . "\n";
711 }
712 $ul .= '</ul>';
713 $liContents = wfMessage( 'linkstoimage-redirect' )->rawParams(
714 $link, $ul )->parse();
715 }
716 $wgOut->addHTML( Html::rawElement(
717 'li',
718 array( 'id' => 'mw-imagepage-linkstoimage-ns' . $element->page_namespace ),
719 $liContents
720 ) . "\n"
721 );
722
723 };
724 $wgOut->addHTML( Html::closeElement( 'ul' ) . "\n" );
725 $res->free();
726
727 // Add a links to [[Special:Whatlinkshere]]
728 if ( $count > $limit ) {
729 $wgOut->addWikiMsg( 'morelinkstoimage', $this->getTitle()->getPrefixedDBkey() );
730 }
731 $wgOut->addHTML( Html::closeElement( 'div' ) . "\n" );
732 }
733
734 protected function imageDupes() {
735 global $wgOut, $wgLang;
736
737 $this->loadFile();
738
739 $dupes = $this->mPage->getDuplicates();
740 if ( count( $dupes ) == 0 ) {
741 return;
742 }
743
744 $wgOut->addHTML( "<div id='mw-imagepage-section-duplicates'>\n" );
745 $wgOut->addWikiMsg( 'duplicatesoffile',
746 $wgLang->formatNum( count( $dupes ) ), $this->getTitle()->getDBkey()
747 );
748 $wgOut->addHTML( "<ul class='mw-imagepage-duplicates'>\n" );
749
750 foreach ( $dupes as $file ) {
751 $fromSrc = '';
752 if ( $file->isLocal() ) {
753 $link = Linker::link(
754 $file->getTitle(),
755 null,
756 array(),
757 array(),
758 array( 'known', 'noclasses' )
759 );
760 } else {
761 $link = Linker::makeExternalLink( $file->getDescriptionUrl(),
762 $file->getTitle()->getPrefixedText() );
763 $fromSrc = wfMsg( 'shared-repo-from', $file->getRepo()->getDisplayName() );
764 }
765 $wgOut->addHTML( "<li>{$link} {$fromSrc}</li>\n" );
766 }
767 $wgOut->addHTML( "</ul></div>\n" );
768 }
769
770 /**
771 * Delete the file, or an earlier version of it
772 */
773 public function delete() {
774 global $wgUploadMaintenance;
775 if ( $wgUploadMaintenance && $this->getTitle() && $this->getTitle()->getNamespace() == NS_FILE ) {
776 global $wgOut;
777 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n", array( 'filedelete-maintenance' ) );
778 return;
779 }
780
781 $this->loadFile();
782 if ( !$this->mPage->getFile()->exists() || !$this->mPage->getFile()->isLocal() || $this->mPage->getFile()->getRedirected() ) {
783 // Standard article deletion
784 parent::delete();
785 return;
786 }
787 $deleter = new FileDeleteForm( $this->mPage->getFile() );
788 $deleter->execute();
789 }
790
791 /**
792 * Display an error with a wikitext description
793 *
794 * @param $description String
795 */
796 function showError( $description ) {
797 global $wgOut;
798 $wgOut->setPageTitle( wfMsg( 'internalerror' ) );
799 $wgOut->setRobotPolicy( 'noindex,nofollow' );
800 $wgOut->setArticleRelated( false );
801 $wgOut->enableClientCache( false );
802 $wgOut->addWikiText( $description );
803 }
804
805 /**
806 * Callback for usort() to do link sorts by (namespace, title)
807 * Function copied from Title::compare()
808 *
809 * @param $a object page to compare with
810 * @param $b object page to compare with
811 * @return Integer: result of string comparison, or namespace comparison
812 */
813 protected function compare( $a, $b ) {
814 if ( $a->page_namespace == $b->page_namespace ) {
815 return strcmp( $a->page_title, $b->page_title );
816 } else {
817 return $a->page_namespace - $b->page_namespace;
818 }
819 }
820 }
821
822 /**
823 * Builds the image revision log shown on image pages
824 *
825 * @ingroup Media
826 */
827 class ImageHistoryList {
828
829 /**
830 * @var Title
831 */
832 protected $title;
833
834 /**
835 * @var File
836 */
837 protected $img;
838
839 /**
840 * @var ImagePage
841 */
842 protected $imagePage;
843
844 protected $repo, $showThumb;
845 protected $preventClickjacking = false;
846
847 /**
848 * @param ImagePage $imagePage
849 */
850 public function __construct( $imagePage ) {
851 global $wgShowArchiveThumbnails;
852 $this->current = $imagePage->getFile();
853 $this->img = $imagePage->getDisplayedFile();
854 $this->title = $imagePage->getTitle();
855 $this->imagePage = $imagePage;
856 $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
857 }
858
859 public function getImagePage() {
860 return $this->imagePage;
861 }
862
863 public function getFile() {
864 return $this->img;
865 }
866
867 public function beginImageHistoryList( $navLinks = '' ) {
868 global $wgOut, $wgUser;
869 return Xml::element( 'h2', array( 'id' => 'filehistory' ), wfMsg( 'filehist' ) ) . "\n"
870 . "<div id=\"mw-imagepage-section-filehistory\">\n"
871 . $wgOut->parse( wfMsgNoTrans( 'filehist-help' ) )
872 . $navLinks . "\n"
873 . Xml::openElement( 'table', array( 'class' => 'wikitable filehistory' ) ) . "\n"
874 . '<tr><td></td>'
875 . ( $this->current->isLocal() && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ? '<td></td>' : '' )
876 . '<th>' . wfMsgHtml( 'filehist-datetime' ) . '</th>'
877 . ( $this->showThumb ? '<th>' . wfMsgHtml( 'filehist-thumb' ) . '</th>' : '' )
878 . '<th>' . wfMsgHtml( 'filehist-dimensions' ) . '</th>'
879 . '<th>' . wfMsgHtml( 'filehist-user' ) . '</th>'
880 . '<th>' . wfMsgHtml( 'filehist-comment' ) . '</th>'
881 . "</tr>\n";
882 }
883
884 public function endImageHistoryList( $navLinks = '' ) {
885 return "</table>\n$navLinks\n</div>\n";
886 }
887
888 /**
889 * @param $iscur
890 * @param $file File
891 * @return string
892 */
893 public function imageHistoryLine( $iscur, $file ) {
894 global $wgUser, $wgLang, $wgContLang;
895
896 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
897 $img = $iscur ? $file->getName() : $file->getArchiveName();
898 $user = $file->getUser( 'id' );
899 $usertext = $file->getUser( 'text' );
900 $description = $file->getDescription();
901
902 $local = $this->current->isLocal();
903 $row = $selected = '';
904
905 // Deletion link
906 if ( $local && ( $wgUser->isAllowedAny( 'delete', 'deletedhistory' ) ) ) {
907 $row .= '<td>';
908 # Link to remove from history
909 if ( $wgUser->isAllowed( 'delete' ) ) {
910 $q = array( 'action' => 'delete' );
911 if ( !$iscur ) {
912 $q['oldimage'] = $img;
913 }
914 $row .= Linker::link(
915 $this->title,
916 wfMsgHtml( $iscur ? 'filehist-deleteall' : 'filehist-deleteone' ),
917 array(), $q, array( 'known' )
918 );
919 }
920 # Link to hide content. Don't show useless link to people who cannot hide revisions.
921 $canHide = $wgUser->isAllowed( 'deleterevision' );
922 if ( $canHide || ( $wgUser->isAllowed( 'deletedhistory' ) && $file->getVisibility() ) ) {
923 if ( $wgUser->isAllowed( 'delete' ) ) {
924 $row .= '<br />';
925 }
926 // If file is top revision or locked from this user, don't link
927 if ( $iscur || !$file->userCan( File::DELETED_RESTRICTED ) ) {
928 $del = Linker::revDeleteLinkDisabled( $canHide );
929 } else {
930 list( $ts, $name ) = explode( '!', $img, 2 );
931 $query = array(
932 'type' => 'oldimage',
933 'target' => $this->title->getPrefixedText(),
934 'ids' => $ts,
935 );
936 $del = Linker::revDeleteLink( $query,
937 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
938 }
939 $row .= $del;
940 }
941 $row .= '</td>';
942 }
943
944 // Reversion link/current indicator
945 $row .= '<td>';
946 if ( $iscur ) {
947 $row .= wfMsgHtml( 'filehist-current' );
948 } elseif ( $local && $wgUser->isLoggedIn() && $this->title->userCan( 'edit' ) ) {
949 if ( $file->isDeleted( File::DELETED_FILE ) ) {
950 $row .= wfMsgHtml( 'filehist-revert' );
951 } else {
952 $row .= Linker::link(
953 $this->title,
954 wfMsgHtml( 'filehist-revert' ),
955 array(),
956 array(
957 'action' => 'revert',
958 'oldimage' => $img,
959 'wpEditToken' => $wgUser->editToken( $img )
960 ),
961 array( 'known', 'noclasses' )
962 );
963 }
964 }
965 $row .= '</td>';
966
967 // Date/time and image link
968 if ( $file->getTimestamp() === $this->img->getTimestamp() ) {
969 $selected = "class='filehistory-selected'";
970 }
971 $row .= "<td $selected style='white-space: nowrap;'>";
972 if ( !$file->userCan( File::DELETED_FILE ) ) {
973 # Don't link to unviewable files
974 $row .= '<span class="history-deleted">' . $wgLang->timeAndDate( $timestamp, true ) . '</span>';
975 } elseif ( $file->isDeleted( File::DELETED_FILE ) ) {
976 if ( $local ) {
977 $this->preventClickjacking();
978 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
979 # Make a link to review the image
980 $url = Linker::link(
981 $revdel,
982 $wgLang->timeAndDate( $timestamp, true ),
983 array(),
984 array(
985 'target' => $this->title->getPrefixedText(),
986 'file' => $img,
987 'token' => $wgUser->editToken( $img )
988 ),
989 array( 'known', 'noclasses' )
990 );
991 } else {
992 $url = $wgLang->timeAndDate( $timestamp, true );
993 }
994 $row .= '<span class="history-deleted">' . $url . '</span>';
995 } else {
996 $url = $iscur ? $this->current->getUrl() : $this->current->getArchiveUrl( $img );
997 $row .= Xml::element( 'a', array( 'href' => $url ), $wgLang->timeAndDate( $timestamp, true ) );
998 }
999 $row .= "</td>";
1000
1001 // Thumbnail
1002 if ( $this->showThumb ) {
1003 $row .= '<td>' . $this->getThumbForLine( $file ) . '</td>';
1004 }
1005
1006 // Image dimensions + size
1007 $row .= '<td>';
1008 $row .= htmlspecialchars( $file->getDimensionsString() );
1009 $row .= ' <span style="white-space: nowrap;">(' . Linker::formatSize( $file->getSize() ) . ')</span>';
1010 $row .= '</td>';
1011
1012 // Uploading user
1013 $row .= '<td>';
1014 // Hide deleted usernames
1015 if ( $file->isDeleted( File::DELETED_USER ) ) {
1016 $row .= '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1017 } else {
1018 if ( $local ) {
1019 $row .= Linker::userLink( $user, $usertext ) . ' <span style="white-space: nowrap;">' .
1020 Linker::userToolLinks( $user, $usertext ) . '</span>';
1021 } else {
1022 $row .= htmlspecialchars( $usertext );
1023 }
1024 }
1025 $row .= '</td>';
1026
1027 // Don't show deleted descriptions
1028 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1029 $row .= '<td><span class="history-deleted">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span></td>';
1030 } else {
1031 $row .= '<td dir="' . $wgContLang->getDir() . '">' . Linker::commentBlock( $description, $this->title ) . '</td>';
1032 }
1033
1034 $rowClass = null;
1035 wfRunHooks( 'ImagePageFileHistoryLine', array( $this, $file, &$row, &$rowClass ) );
1036 $classAttr = $rowClass ? " class='$rowClass'" : '';
1037
1038 return "<tr{$classAttr}>{$row}</tr>\n";
1039 }
1040
1041 /**
1042 * @param $file File
1043 * @return string
1044 */
1045 protected function getThumbForLine( $file ) {
1046 global $wgLang;
1047
1048 if ( $file->allowInlineDisplay() && $file->userCan( File::DELETED_FILE ) && !$file->isDeleted( File::DELETED_FILE ) ) {
1049 $params = array(
1050 'width' => '120',
1051 'height' => '120',
1052 );
1053 $timestamp = wfTimestamp( TS_MW, $file->getTimestamp() );
1054
1055 $thumbnail = $file->transform( $params );
1056 $options = array(
1057 'alt' => wfMsg( 'filehist-thumbtext',
1058 $wgLang->timeAndDate( $timestamp, true ),
1059 $wgLang->date( $timestamp, true ),
1060 $wgLang->time( $timestamp, true ) ),
1061 'file-link' => true,
1062 );
1063
1064 if ( !$thumbnail ) {
1065 return wfMsgHtml( 'filehist-nothumb' );
1066 }
1067
1068 return $thumbnail->toHtml( $options );
1069 } else {
1070 return wfMsgHtml( 'filehist-nothumb' );
1071 }
1072 }
1073
1074 protected function preventClickjacking( $enable = true ) {
1075 $this->preventClickjacking = $enable;
1076 }
1077
1078 public function getPreventClickjacking() {
1079 return $this->preventClickjacking;
1080 }
1081 }
1082
1083 class ImageHistoryPseudoPager extends ReverseChronologicalPager {
1084 protected $preventClickjacking = false;
1085
1086 /**
1087 * @var File
1088 */
1089 protected $mImg;
1090
1091 /**
1092 * @var Title
1093 */
1094 protected $mTitle;
1095
1096 /**
1097 * @param ImagePage $imagePage
1098 */
1099 function __construct( $imagePage ) {
1100 parent::__construct();
1101 $this->mImagePage = $imagePage;
1102 $this->mTitle = clone ( $imagePage->getTitle() );
1103 $this->mTitle->setFragment( '#filehistory' );
1104 $this->mImg = null;
1105 $this->mHist = array();
1106 $this->mRange = array( 0, 0 ); // display range
1107 }
1108
1109 function getTitle() {
1110 return $this->mTitle;
1111 }
1112
1113 function getQueryInfo() {
1114 return false;
1115 }
1116
1117 function getIndexField() {
1118 return '';
1119 }
1120
1121 function formatRow( $row ) {
1122 return '';
1123 }
1124
1125 function getBody() {
1126 $s = '';
1127 $this->doQuery();
1128 if ( count( $this->mHist ) ) {
1129 $list = new ImageHistoryList( $this->mImagePage );
1130 # Generate prev/next links
1131 $navLink = $this->getNavigationBar();
1132 $s = $list->beginImageHistoryList( $navLink );
1133 // Skip rows there just for paging links
1134 for ( $i = $this->mRange[0]; $i <= $this->mRange[1]; $i++ ) {
1135 $file = $this->mHist[$i];
1136 $s .= $list->imageHistoryLine( !$file->isOld(), $file );
1137 }
1138 $s .= $list->endImageHistoryList( $navLink );
1139
1140 if ( $list->getPreventClickjacking() ) {
1141 $this->preventClickjacking();
1142 }
1143 }
1144 return $s;
1145 }
1146
1147 function doQuery() {
1148 if ( $this->mQueryDone ) {
1149 return;
1150 }
1151 $this->mImg = $this->mImagePage->getFile(); // ensure loading
1152 if ( !$this->mImg->exists() ) {
1153 return;
1154 }
1155 $queryLimit = $this->mLimit + 1; // limit plus extra row
1156 if ( $this->mIsBackwards ) {
1157 // Fetch the file history
1158 $this->mHist = $this->mImg->getHistory( $queryLimit, null, $this->mOffset, false );
1159 // The current rev may not meet the offset/limit
1160 $numRows = count( $this->mHist );
1161 if ( $numRows <= $this->mLimit && $this->mImg->getTimestamp() > $this->mOffset ) {
1162 $this->mHist = array_merge( array( $this->mImg ), $this->mHist );
1163 }
1164 } else {
1165 // The current rev may not meet the offset
1166 if ( !$this->mOffset || $this->mImg->getTimestamp() < $this->mOffset ) {
1167 $this->mHist[] = $this->mImg;
1168 }
1169 // Old image versions (fetch extra row for nav links)
1170 $oiLimit = count( $this->mHist ) ? $this->mLimit : $this->mLimit + 1;
1171 // Fetch the file history
1172 $this->mHist = array_merge( $this->mHist,
1173 $this->mImg->getHistory( $oiLimit, $this->mOffset, null, false ) );
1174 }
1175 $numRows = count( $this->mHist ); // Total number of query results
1176 if ( $numRows ) {
1177 # Index value of top item in the list
1178 $firstIndex = $this->mIsBackwards ?
1179 $this->mHist[$numRows - 1]->getTimestamp() : $this->mHist[0]->getTimestamp();
1180 # Discard the extra result row if there is one
1181 if ( $numRows > $this->mLimit && $numRows > 1 ) {
1182 if ( $this->mIsBackwards ) {
1183 # Index value of item past the index
1184 $this->mPastTheEndIndex = $this->mHist[0]->getTimestamp();
1185 # Index value of bottom item in the list
1186 $lastIndex = $this->mHist[1]->getTimestamp();
1187 # Display range
1188 $this->mRange = array( 1, $numRows - 1 );
1189 } else {
1190 # Index value of item past the index
1191 $this->mPastTheEndIndex = $this->mHist[$numRows - 1]->getTimestamp();
1192 # Index value of bottom item in the list
1193 $lastIndex = $this->mHist[$numRows - 2]->getTimestamp();
1194 # Display range
1195 $this->mRange = array( 0, $numRows - 2 );
1196 }
1197 } else {
1198 # Setting indexes to an empty string means that they will be
1199 # omitted if they would otherwise appear in URLs. It just so
1200 # happens that this is the right thing to do in the standard
1201 # UI, in all the relevant cases.
1202 $this->mPastTheEndIndex = '';
1203 # Index value of bottom item in the list
1204 $lastIndex = $this->mIsBackwards ?
1205 $this->mHist[0]->getTimestamp() : $this->mHist[$numRows - 1]->getTimestamp();
1206 # Display range
1207 $this->mRange = array( 0, $numRows - 1 );
1208 }
1209 } else {
1210 $firstIndex = '';
1211 $lastIndex = '';
1212 $this->mPastTheEndIndex = '';
1213 }
1214 if ( $this->mIsBackwards ) {
1215 $this->mIsFirst = ( $numRows < $queryLimit );
1216 $this->mIsLast = ( $this->mOffset == '' );
1217 $this->mLastShown = $firstIndex;
1218 $this->mFirstShown = $lastIndex;
1219 } else {
1220 $this->mIsFirst = ( $this->mOffset == '' );
1221 $this->mIsLast = ( $numRows < $queryLimit );
1222 $this->mLastShown = $lastIndex;
1223 $this->mFirstShown = $firstIndex;
1224 }
1225 $this->mQueryDone = true;
1226 }
1227
1228 protected function preventClickjacking( $enable = true ) {
1229 $this->preventClickjacking = $enable;
1230 }
1231
1232 public function getPreventClickjacking() {
1233 return $this->preventClickjacking;
1234 }
1235
1236 }